//
//  USAlbumEditController.m
//  us
//
//  Created by karry on 2025/4/11.
//

#import "USAlbumEditController.h"
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
#import "Album+CoreDataProperties.h"
#import "USMediaUploadManager.h"
@interface USAlbumEditController ()

@property (nonatomic,strong) UIButton *editPhotoBtn;
@property (nonatomic,strong) UITextField *tf;

@end

@implementation USAlbumEditController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"相册名称";
    [self setupView];
    
    if (self.album && self.album.albumId.length > 0) {
        self.editing = YES;
    }
    if (self.isEditing) {
        self.tf.text = self.album.albumName;
    }
}

- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
    }
    return _imageView;
}


- (void)setupView{

    
    self.imageView.image = self.image;
    [self.view addSubview:self.imageView];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(144);
        make.height.mas_equalTo(176.84);
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).mas_offset(20);
    }];
    
    //编辑相册模式才会显示
    self.editPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editPhotoBtn.alpha = self.isEditing ? 1 : 0;
    [self.editPhotoBtn addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchDragInside];
    [self.editPhotoBtn setImage:[UIImage imageNamed:@"Frame 58"] forState:0];
    [self.view addSubview:self.editPhotoBtn];
    [self.editPhotoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.imageView.mas_right).mas_offset(-8);
        make.bottom.mas_equalTo(self.imageView.mas_bottom).mas_offset(-8);
    }];
    
    UITextField *tf = [[UITextField alloc]initWithFrame:CGRectZero];
    _tf = tf;
    tf.placeholder = @"请输入相册名称";
    tf.layer.cornerRadius = 14;
    tf.textAlignment = NSTextAlignmentCenter;
    tf.layer.borderWidth = 1.6;
    tf.layer.borderColor = UIColor.clearColor.CGColor;
    tf.backgroundColor = [UIColor mi_3_color];
    UIView *leftPadding = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 1)];
    tf.leftView = leftPadding;
    tf.leftViewMode = UITextFieldViewModeAlways;

    UIView *rightPadding = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 1)];
    tf.rightView = rightPadding;
    tf.rightViewMode = UITextFieldViewModeAlways;
    tf.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
    tf.jk_maxLength = 80;
    [self.view addSubview:tf];
    
    [tf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(24);
        make.right.mas_offset(-24);
        make.height.mas_equalTo(65);
        make.top.mas_equalTo(self.imageView.mas_bottom).mas_offset(30);
    }];

    [[tf rac_signalForControlEvents:UIControlEventEditingDidBegin]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.layer.borderColor = UIColor.us_blueColor.CGColor;
    }];
    
    [[tf rac_signalForControlEvents:UIControlEventEditingDidEnd]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.layer.borderColor = UIColor.clearColor.CGColor;
    }];
    
    [tf becomeFirstResponder];

    self.navigationItem.rightBarButtonItem = self.doneItem;
    
    RAC(self.doneItem, enabled) = [tf.rac_textSignal map:^id _Nullable(NSString * _Nullable text) {
        return @(text.length > 0);
    }];
    
}

- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.doneItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)doneAction:(id)sender{
    [super doneAction:sender];
    
        UIImage *cover = self.imageNoLine;
//    UIImage *cover = self.image;
    
    [self startUpload];
    
    
    [USMediaUploadManager uploadImageToCOS:cover progress:^(CGFloat progress) {
        
    } success:^(NSString * _Nonnull cosUrl) {
        
        NSLog(@"图片上传成功");
        
        [self addAlubumWithCoverUrlPath:cosUrl];
        
    } failure:^(NSError * _Nonnull error) {
        
        [self.view us_makeAlert:error.localizedDescription subTitle:nil];
        [self endUpLoad];
    }];
    
    
}

- (void)addAlubumWithCoverUrlPath:(NSString *)path{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"albumDescribe"] = @"";
    params[@"albumName"] = self.tf.text;
    params[@"coverUrl"] = path;
    params[@"sharedSpaceId"] = USUser.user.sharedSpaceId;
    params[@"color"] = self.colorHex;
    params[@"coverType"] = @(self.coverType);

    if (self.isEditing) {
        params[@"albumId"] = self.album.albumId;
    }else {
        params[@"gmtCreate"] = @((NSInteger)NSDate.date.timeIntervalSince1970);
    }
    @weakify(self)
    [[EMNetWork shareManager] em_post:self.isEditing ? API_AlbumEdit : API_AlbumCreate
                               params:params
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        @strongify(self)
        [self endUpLoad];
        if (api.success) {
            
            if (!self.isEditing) {
                [USCoreDataStack.shared.context performBlockAndWait:^{
                    
                    Album *model = [Album jk_create:USCoreDataStack.shared.context];
                    [model mj_setKeyValues:api.data[@"Album"]];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"USNotificationNameAddAlbumSuccess" object:model.albumId];
        
                }];
            }
     
            [self addSuccess];
            
        } else {
            NSLog(@"添加失败：%@", api.msg);
        }
    } fail:^{
        @strongify(self)
        [self endUpLoad];
        NSLog(@"网络请求失败");
    }];
    
}




- (void)addSuccess{
    
    [USFeedbackTool notifySuccess];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

 

- (void)editAction:(id)sender{
    
    
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
